import React, { Component } from 'react';
import {
    View, Text, StyleSheet, TouchableOpacity, Image, ScrollView, Modal, ActivityIndicator, PixelRatio
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import DatePicker from 'react-native-datepicker'
import navigationSeevice from '../../../../components/navigation/navigationSeevice';
import { API, API_GENERATE } from '../../../../config/api';
import Upload from '../../../../utils/Upload';
import HTTP from '../../../../utils/http';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import ModalPicDelComponent from '../../../../component/ModalPicDelComponent';
import { enterpriseStyles } from '../../_common/enterpriseStyle';
import { Common } from '../../../../component/common/Common'
import { LargeBtn } from '../../../requirement-plan/component/Component.js';
import DateGapPicker from '../../../../components/common/DateGapPicker';
import ToastUtil from '../../../../utils/toast';

const scale = GLOBAL.SCALE;
const uploadPic = require('../../../../imgs/store/upload.png');
let selectIcon = require('../../../../imgs/select.png');
let deleteIcon = require('../../../../imgs/delete.png');

const modalPicDelCfg = {
    visible: false,
    uri: null,
    delPress: () => { },
    picPress: () => { },
    fileId: '',
    delTextHide: true
}

export class EnterpriseEditQualificationPage extends Component {
    static navigationOptions = ({ navigation }) => {
        const params = navigation.state.params || {};
        const { companyName } = params;
        return {
            headerTitle: companyName,
            headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
            headerTintColor: style.color.white,
            headerStyle: {
                elevation: 0,
                borderBottomWidth: 0,
                backgroundColor: style.color.themeColor,
            },
            headerTitleStyle: {
                textAlign: 'center',
            }
        };
    };

    constructor(props) {
        super(props);
        const { companyName, qualificationVO, qualificationType, ifEdit, qualificationInfo } = props.navigation.state.params;
        const { expireDate } = qualificationInfo || {};
        const { companyId } = qualificationVO || {};
        const { dictKey, dictName } = qualificationType || {};
        this.ifEdit = ifEdit;
        this.qualificationInfo = qualificationInfo;
        console.log('ifEdit', ifEdit)
        this.selectPhotoTapped = this.selectPhotoTapped.bind(this);
        this.sendData = {
            qualificationList: [{
                companyId,
                qualificationType: dictKey
            }],
            bizType: 'COMPANY_QUALIFI_INFO',
            companyInfoVO: {
                companyId,
                companyName
            },
        };

        modalPicDelCfg.picPress = () => {
            modalPicDelCfg.visible = false;
            modalPicDelCfg.uri = null;
            this.setState({
                previewModalVisible: false,
            });
        }

        this.state = {
            loadQualification: true,
            previewModalVisible: false,
            qualificationTypeObj: { name: dictName, uriList: [] },
            loaded: false,
            beginDate: expireDate && expireDate.substring(0, 10) || '',
            expireDate: expireDate && expireDate.substring(0, 10) || ''
        }
    }

    async componentWillMount() {
        const { qualificationAddress } = this.qualificationInfo;
        qualificationAddress && this.getImgView(qualificationAddress);

        this.setState({
            loadQualification: false,
        });
    }

    componentWillUnmount() {
        this.setState({
            loaded: false,
        });
    }

    //提前获取资质图片
    getImgView(qualificationAddress) {
        if (!qualificationAddress) return;
        this.setState({ loaded: true })
        const qualificationArr = qualificationAddress.split(',');
        qualificationArr.map(async (fileId, index) => {
            await this.loadedImgs(fileId, qualificationArr.length, index);
        })
    }
    async	loadedImgs(fileId, length, index) {
        const { qualificationTypeObj } = this.state;
        const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
        if (response) {
            const { attachmentFileVO } = response;
            qualificationTypeObj.uriList.push({
                uri: response.image || '',
                type: attachmentFileVO.fileExtName.toUpperCase() || 'PNG',
                fileId
            });

            if (qualificationTypeObj.uriList.length == length) {
                this.setState({
                    loaded: false,
                });
            }
        } else {
            // qualificationTypeObj.uriList.push({
            //     uploadPic,
            //     type: 'ERROR',
            //     fileId
            // });
            this.setState({ loaded: false })
        }
    }

	/**
 * 上传图片
 * @param {String} attachment 统一社会信用证文件 分类
 * @param {String} ocrType 分类
 */
    selectPhotoTapped(ocrType) {
        let imgRep = {};
        const options = {
            title: '请选择图片来源',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '相册图片',
            quality: 1.0,
            maxWidth: 500,
            maxHeight: 500,
            storageOptions: {
                skipBackup: true,
                // path: 'images'
            },
            mediaType: 'photo',
        };
        ImagePicker.showImagePicker(options, async (response) => {
            const { qualificationTypeObj } = this.state;

            if (response.didCancel) {
                console.log('User cancelled photo picker');
                return;
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
                return;
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
                return;
            }
            else {
                imgRep.uri = response.uri;

                this.setState({
                    loaded: true
                });
            }

            const uploadImgObj = {
                imgUrl: { uri: response.uri },
                url: API_GENERATE(API.IMG_UPLOAD)
            }
            if (ocrType && ocrType.length) {
                uploadImgObj.ocrType = ocrType;
                uploadImgObj.isOcr = 1;
            } else {
                uploadImgObj.isOcr = 0
            }
            let responseData = await Upload.uploadImg(uploadImgObj);

            if (responseData) {
                if (responseData.fileId) {
                    imgRep.fileId = responseData.fileId;
                    imgRep.type = 'PNG';
                    qualificationTypeObj.uriList.push(imgRep);
                }
            }
            this.setState({
                loaded: false
            })
        });
    }

    //删除图片
    async _delete(index, fileId) {
        const { qualificationTypeObj } = this.state;
        const { uriList } = qualificationTypeObj;
        if (!fileId) return;
        let responseData = await HTTP.POST(API_GENERATE(API.DELETE_FILE) + '?fileId=' + fileId, {});

        modalPicDelCfg.visible = false;
        modalPicDelCfg.uri = null;
        uriList.splice(index, 1);
        qualificationTypeObj.uriList = uriList;
        this.setState({ qualificationTypeObj });

    }

    async _didPressLargeBtn() {
        const { qualificationTypeObj, expireDate, beginDate } = this.state;
        const { name, uriList } = qualificationTypeObj;
        if (!uriList.length) {
            ToastUtil.showInfo('请上传资质:' + name);
            return;
        }

        let addr = '';
        uriList.forEach((item, i) => {
            if (item) {
                addr += (i === 0 ? '' : ',') + item.fileId;
            }
        })

        this.sendData.qualificationList[0].qualificationAddress = addr;
        this.sendData.qualificationList[0].beginDate = beginDate;
        this.sendData.qualificationList[0].expireDate = expireDate;
        // if (!beginDate) {
        //     ToastUtil.showInfo('请选择资质开始日期');
        //     return;
        // }
        if (!expireDate) {
            ToastUtil.showInfo('请选择资质结束日期');
            return;
        }
        // if (new Date(expireDate) < new Date(beginDate)) {
        //     ToastUtil.showInfo('开始日期不能大于结束日期');
        //     return;
        // }
        this.setState({ loaded: true })
        const responseData = await HTTP.POST(API_GENERATE(API.UPDATE_CUSTOMER_INFO), this.sendData);
        this.setState({ loaded: false })
        if (responseData) {
            ToastUtil.showSuccess('您添加的资质已提交,请耐心等待审核');
            this.timer = setTimeout(() => {
                this._goBack();
            }, 800)
        }
    }

    // 返回上一个页面
    _goBack = () => {
        const { navigate } = this.props.navigation;
        navigate('EnterpriseDetailsPage');
    }

    _renderQualificationImg() {
        const { loadQualification, qualificationTypeObj, beginDate, expireDate } = this.state;
        const { uriList } = qualificationTypeObj || {};
        if (loadQualification) return null;
        const picViews = uriList.length ? uriList.map((item, i) => {
            const { uri, fileId, type } = item;
            return (
                <TouchableOpacity key={i} style={[enterpriseStyles.attachment, styles.uploadImgBox]}
                    onPress={() => {
                        if (type == 'PDF') {
                            navigationSeevice.navigate('ContractPdfPage', {
                                finalFileId: fileId,
                                title: '附件信息'
                            })
                        } else {
                            modalPicDelCfg.visible = true;
                            modalPicDelCfg.uri = uri;
                            modalPicDelCfg.fileId = fileId;
                            this.setState({
                                ls: true
                            })
                        }
                    }} activeOpacity={0.5}>
                    {this.ifEdit ? <TouchableOpacity onPress={this._delete.bind(this, i, fileId)} style={{ zIndex: 10 }}>
                        <Image style={styles.close} source={deleteIcon} />
                    </TouchableOpacity> : null}
                    {
                        type == 'PDF' ?
                            <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap' }}>
                                <Text>PDF文件</Text><Text>点击可查看</Text>
                            </View>
                            : <Image source={type == 'ERROR' ? deleteIcon : item} style={enterpriseStyles.cover} />
                    }
                </TouchableOpacity>
            )
        }) : null;

        return (
            <View styles={{ flex: 1 }}>
                <View style={enterpriseStyles.attachmentRow}>
                    {picViews}
                    {this.ifEdit ? <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
                        this.selectPhotoTapped(0);
                    }} activeOpacity={0.5} >
                        <Image source={uploadPic} style={enterpriseStyles.cover} />
                    </TouchableOpacity> : null}
                </View>

                <View style={enterpriseStyles.selectContainer}>
                    <View style={styles.boxUp}>
                        <Text style={styles.label}><Text style={styles.require}>{this.ifEdit && '* '}</Text> 有效期至</Text>
                        <View style={styles.rowStyle}>
                            {/* <DatePicker
                                style={{ width: 128 }}
                                date={beginDate}
                                mode="date"
                                placeholder="请选择开始日期"
                                format="YYYY-MM-DD"
                                confirmBtnText="确认"
                                cancelBtnText="取消"
                                customStyles={{
                                    dateIcon: { opacity: 0, width: 0 },
                                    dateInput: {
                                        marginLeft: 0, borderWidth: 0, alignItems: 'center'
                                    }
                                }
                                }
                                onDateChange={(date) => { this._setTimeCallback(date, 'beginDate'); }}
                            /> */}
                            {/* <Text style={{ marginRight: 5 * scale }}>-</Text> */}
                            <DatePicker
                                style={{ width: 128 }}
                                date={expireDate}
                                mode="date"
                                placeholder="请选择结束日期"
                                format="YYYY-MM-DD"
                                confirmBtnText="确认"
                                cancelBtnText="取消"
                                customStyles={{
                                    dateIcon: { opacity: 0, width: 0 },
                                    dateInput: {
                                        marginLeft: 0, borderWidth: 0, alignItems: 'center'
                                    }
                                }
                                }
                                onDateChange={(date) => { this._setTimeCallback(date, 'expireDate'); }}
                            />
                        </View>
                    </View>
                </View>
            </View>
        );
    }

    _setTimeCallback = (date, type) => {
        this.setState({
            beginDate: type === 'beginDate' ? date : this.state.beginDate,
            expireDate: type === 'expireDate' ? date : this.state.expireDate
        })
    }

    render() {
        let { loaded } = this.state;
        let qualificationListView = this._renderQualificationImg();
        return (
            <ScrollView style={styles.scrollView} >
                <View style={[{ paddingLeft: 12 * scale, paddingTop: 40 * scale, paddingBottom: 40 * scale }]}>
                    <Text style={enterpriseStyles.lableText}>{this.props.navigation.state.params.qualificationType.dictName}</Text>
                </View>
                <View style={styles.container}>
                    <ModalPicDelComponent {...modalPicDelCfg} />
                    <View style={styles.wrap}>
                        {qualificationListView}
                    </View>

                    {this.ifEdit ? <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                        <TouchableOpacity style={enterpriseStyles.button} onPress={() => this._didPressLargeBtn()}>
                            <Text style={enterpriseStyles.buttonText}>提交</Text>
                        </TouchableOpacity>
                    </View> : null}
                </View>

                <Modal animationType={"fade"}
                    transparent={true}
                    visible={loaded}
                    onRequestClose={() => { }}>
                    <View style={styles.ocrWrap}>
                        <View style={styles.loadedCell}><ActivityIndicator
                            animating={true}
                            color={'#fff'}
                            size="small"
                        /></View>
                    </View>
                </Modal>
            </ScrollView>
        )
    }

}

const styles = StyleSheet.create({
    scrollView: {
        flex: 1,
        backgroundColor: '#fff',
    },
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#fff',
    },
    wrap: {
        width: 345 * scale,
    },
    closeTextCell: {
        position: 'absolute',
        left: 8,
        top: 0,
    },
    productText: {
        fontSize: 14 * scale,
        color: '#404040',
        marginBottom: 8 * scale,
        paddingTop: 14 * scale,
        lineHeight: 14 * scale,
    },
    ocrWrap: {
        width: 375 * scale,
        height: GLOBAL.SCREEN_HEIGHT,
        backgroundColor: 'rgba(0, 0, 0, 0)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadedCell: {
        width: 75 * scale,
        height: 75 * scale,
        backgroundColor: 'rgba(0, 0, 0, .5)',
        borderRadius: 7,
        justifyContent: 'center',
        alignItems: 'center',
    },
    boxUp: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingTop: 15 * scale,
        paddingBottom: 15 * scale,
    },
    label: {
        width: 70 * scale,
        color: '#333',
        fontSize: 14 * scale
    },
    require: {
        fontSize: 14 * scale,
        color: '#D0021B',
    },
    rowStyle: {
        // flex: 1,
        flexDirection: 'row',
        alignItems: 'center'
    },
    xianBox: {
        width: 108 * scale,
    },
    xian: {
        marginLeft: 5 * scale,
        marginRight: 5 * scale,
        color: '#222',
        textAlign: 'center',
        fontWeight: 'bold'
    },
    select: {
        tintColor: '#000',
        transform: [{ 'rotate': '-90deg' }]
    },
    uploadImgBox: {
        borderColor: style.color.themeColor,
        borderWidth: 1,
    },
    close: {
        position: 'absolute',
        right: -8 * scale,
        top: -6 * scale,
        width: 12 * scale,
        height: 12 * scale,
        zIndex: 10
    }
})